﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Office.Interop.Word;
using TemplateGenerator.Entities;
using TemplateGenerator.Logic;

namespace TemplateGenerator {
	public static class GeneratorHandler {

		public static Application WordApp;
		public static String ResourceLocation = Environment.CurrentDirectory + "\\Resources\\";

		public static List<CustomTemplate> CustomTemplates { get; set; }

		public static Document GenerateNewDocument(String templateName) {
            //opens new document given as parameter
			Document doc = WordApp.Documents.Add(ResourceLocation + templateName);
			return doc;
		}
		
		public static void LoadTemplates() {
            List<CustomTemplate> templates = new List<CustomTemplate>();

            //gets directory where templates are stored and gets the files ending with .dotx which are not hidden (to filter out temporary files when a template is opened)
            DirectoryInfo directory = new DirectoryInfo(ResourceLocation);
            var files = directory.GetFiles("*.dotx").Where(f => (f.Attributes & FileAttributes.Hidden) == 0);

            //loop all the files, add information in a new customtemplate instance and add those to the templates list
            foreach (FileInfo file in files)
            {
                CustomTemplate template = new CustomTemplate();
                template.Name = file.Name.Replace(file.Extension, "");
                template.Image = "\\Resources\\wordStandard.png";
                template.FilePath = file.FullName;

                //TODO: look at why this refuses to work
                //template.Version.Add(AppProperties.LocalWordVersion);

                templates.Add(template);
            }

            CustomTemplates = templates;
		}		

		public static void FormatDocument(Dictionary<string, string> fieldNValues) {
			FormatDocument(WordApp.ActiveDocument, fieldNValues);
		}

		public static void FormatDocument(Document doc, Dictionary<string, string> fieldNValues) {
			//loops through the given values and places them inside the Word document
            foreach (var field in fieldNValues) {
				SetStringValue(ref doc, field.Key, field.Value);
			}
		}

		private static void SetStringValue(ref Document doc, string fieldName, string value) {
			//loops through all the controls in a Word document with the fieldname parameter and places the value parameter in its text field
            foreach (ContentControl control in doc.SelectContentControlsByTitle(fieldName)) {
				control.SetPlaceholderText(Text: value);
			}
		}

        public static string CopyFile(string path)
        {
            //copy's a file with given path to the resource location where all the templates are saved
            string newDirectory = ResourceLocation + DirectorySplit(path);
            File.Copy(path, newDirectory, true);
            return newDirectory;
        }

        public static bool DeleteFile(string path)
        {
            //looks if given file exists
            if(File.Exists(path))
            {
                try //try/catch in case access to file is denied
                {
                    //set file attributes to normal or there might be a access denied error otherwise
                    File.SetAttributes(path, FileAttributes.Normal);
                    //delete file
                    File.Delete(path);
                    return true;
                }
                catch (IOException ex)
                {
                    Communication.Notify("Template file could not be deleted. Message: " + ex.Message, "Error");
                }
            }

            return false;
        }

        public static string DirectorySplit(string path)
        {
            return path.Split(Path.DirectorySeparatorChar).Last();
        }
	}
}
